

/*
wifi 文档
https://www.arduino.cc/reference/en/libraries/wifi/
*/
#include <ESP8266WiFi.h>

//这是一个预处理指令，用于检查STASSID这个宏是否没有（ifndef即if not defined的缩写）被定义。如果STASSID没有定义，则执行#ifndef和随后的#endif之间的代码
#ifndef STASSID
#define STASSID "wsm"
#define STAPSK "WSM19900509"
#endif

const char* ssid = "MERCURY_394B46";
const char* password = "wifi19900509wifi";
// multi.addAP("MERCURY_394B46", "wifi19900509wifi"); 
const char* host = "http://example.com";
const uint16_t port = 80;

//初始化时使用sta模式连接wifi
void setup() {
  Serial.begin(9600);
  Serial.println("esp8266 Connecting to WIFI ");
  // WiFi.mode(WIFI_STA); //默认就是sta模式 
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(" .");
  }
  Serial.print("esp8266的ip: ");
  Serial.print(WiFi.localIP());
}

void loop() {
  static bool wait = false;

  Serial.println("");
  Serial.print("connecting to ");
  Serial.print(host);
  Serial.print(':');
  Serial.println(port);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    delay(5000);
    return;
  }

  // This will send a string to the server
  Serial.println("sending data to server");
  if (client.connected()) { 
    client.println("hello from ESP8266");
    }

  // wait for data to be available
  unsigned long start = millis();
  while (client.available() == 0) {
    //超过5s时客户端stop
    if (millis() - start > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      delay(60000);
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  Serial.println("receiving from remote server");
  // not testing 'client.connected()' since we do not need to send data here
  while (client.available()) {
    char ch = static_cast<char>(client.read());
    Serial.print(ch);
  }

  // Close the connection
  Serial.println();
  Serial.println("closing connection");
  client.stop();

  if (wait) {
    delay(300000);  // execute once every 5 minutes, don't flood remote service
  }
  wait = true;
}